package com.text.service.impl;

import com.text.entity.Course;
import com.text.entity.Student;
import com.text.entity.StudentAndCourse;
import com.text.repository.StudentAndCourseRepository;
import com.text.repository.StudentRepository;
import com.text.repository.CourseRepository;
import com.text.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private StudentAndCourseRepository studentAndCourseRepository;
    @Override
    public void addStudentWithCourses(Student student, Set<String> courseIds) {
        // 保存学生到数据库
        Student savedStudent = studentRepository.save(student);

        // 保存学生与课程的关系
        for (String courseId : courseIds) {
            StudentAndCourse studentAndCourse = new StudentAndCourse();
            studentAndCourse.setStudentId(savedStudent.getStudentId());
            studentAndCourse.setCourseId(courseId);
            studentAndCourse.setDescription("学生 " + savedStudent.getStudentName() + " 选修了课程 " + courseId);
            studentAndCourseRepository.save(studentAndCourse);
        }
    }

    @Override
    public Student getStudent(String id) {
        return studentRepository.findById(id).orElse(null);
    }

    @Override
    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }



    @Override
    public boolean updateStudent(String id, Student updatedStudent) {
        Optional<Student> existingStudentOptional = studentRepository.findById(id);
        if (existingStudentOptional.isPresent()) {
            Student existingStudent = existingStudentOptional.get();

            // 更新字段
            existingStudent.setStudentName(updatedStudent.getStudentName());
            existingStudent.setStudentGender(updatedStudent.getStudentGender());
            existingStudent.setStudentPhone(updatedStudent.getStudentPhone());
            existingStudent.setMajor(updatedStudent.getMajor());

            // 保存更新后的学生信息
            studentRepository.save(existingStudent);
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteStudent(String id) {
        Optional<Student> existingStudent = studentRepository.findById(id);
        if (existingStudent.isPresent()) {
            studentRepository.deleteById(id);
            return true;
        }
        return false;
    }


}